package com.mamba.microservice.filter;

import com.mamba.microservice.context.ContextLogbackUtils;
import com.mamba.microservice.context.ServiceContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import java.io.IOException;

/**
 * Copyright ©2020 360jinrong All Rights Reserved
 * 请添加类/接口的说明：初始化http请求上下文提交
 *
 * @Package: com.mamba.microservice.filter
 * @author: fangjin
 * @date: 2020年04月22日 16时51分
 */
@Slf4j
public class ServiceContextFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.debug("进入ServiceContextFilter初始化上下文信息");
        ServiceContext serviceContext = ServiceContext.getContext();
        String requestNo = serviceContext.getRequestNo();
        if (StringUtils.isEmpty(requestNo)) {
            serviceContext.setRequestNo();
        }
        ContextLogbackUtils.addContext2MDC();
        try {
            chain.doFilter(request, response);
        } catch (Throwable throwable) {
            throw throwable;
        } finally {
            ContextLogbackUtils.removeContextFromMDC();
        }
    }

    @Override
    public void destroy() {

    }
}
